package com.changpei.common.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *
 *
 * @author Way on 2021/8/8
 */
@Slf4j
public class JsonUtil {

    /**
     * Json转为目标对象
     *
     * @param source
     * @param target
     * @param <T>
     * @return
     */
    public static <T> T jsonToBean(Object source, Class<T> clazz) {
        if (null == source) {
            return null;
        } else {
            return JSON.parseObject(JSON.toJSONString(source), clazz);
        }
    }

    /**
     * Json转为集合
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToList(Collection<?> source, Class<T> clazz) {
        if (source.isEmpty()) {
            return new ArrayList<>();
        } else {
            return JSON.parseArray(JSON.toJSONString(source), clazz);
        }
    }

    /**
     * 对象格式化输出
     *
     * @param obj
     */
    public static void prettyPrintByJson(Object obj) {
        StringBuffer sb = new StringBuffer();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            sb.append(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));
            System.out.println(sb);
        } catch (JsonProcessingException e) {
            log.warn("对象格式化输出失败");
        }
    }
}
